package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import im.beans.Message;
import manager.PersistentManager;

/**
 * Servlet implementation class GetMessage
 */
//@WebServlet("/GetMessage")
public class GetMessage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMessage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		
		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data,Upload.class);
		Download download = new Download();
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try{
			Query q = session.createQuery("from Message m where m.toName = ? and m.isRead = ?");
			q.setParameter(0, upload.getUserName());
			q.setParameter(1, false);
			
			List<Message> msgs = q.list();
			Query update = session.createQuery("update Message m set m.isRead = ? where m.toName = ?");
			update.setParameter(0, true);
			update.setParameter(1, upload.getUserName());
			update.executeUpdate();
			
			
			download.setMsgs(getDownloadMsg(msgs));
			session.getTransaction().commit();
			download.setStatus(Download.SUCCESS);
		}catch(Exception e)
		{
			tx.rollback();
			download.setStatus(Download.FAILD);
			e.printStackTrace();
		}finally {
//			session.close();
		}
		
		System.out.println(JSON.toJSONString(download));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(download));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	// 获取下载消息，数据格式转换为客户端上传格式
	private List<SendMessage.Upload> getDownloadMsg(List<Message> msg)
	{
		List<SendMessage.Upload> result = new ArrayList<>();
		for(Message m:msg)
		{
			SendMessage.Upload up = new SendMessage.Upload();
			up.setFrom_id(m.getFrom_id());
			up.setFromMe(SendMessage.Upload.FROMREMOTE);
			up.setFromName(m.getFromName());
			up.setLocal(SendMessage.Upload.FROMREMOTE);
			up.setText(m.getText());
			up.setTimestamp(m.getTimestamp());
			up.setFileName(m.getFileName());
			up.setType(m.getType());
			result.add(up);
		}
		
		return result;
	}
	
	// 上传数据
    public static class Upload
    {
        String id;
        String userName;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }
    
    // 下行数据
    public static class Download
    {
    	
    	public static final String  SUCCESS = "1";
    	public static final String FAILD = "2";
    	
    	String status;
    	List<SendMessage.Upload> msgs;

		public List<SendMessage.Upload> getMsgs() {
			return msgs;
		}

		public void setMsgs(List<SendMessage.Upload> msgs) {
			this.msgs = msgs;
		}

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}
    	
    }
	
}
